package com.ruoyi.framework.utils;

import com.ruoyi.common.constant.OpsConstants;
import com.ruoyi.common.entity.ValidateData;
import com.ruoyi.framework.redis.CacheTool;
import net.dreamlu.mica.core.utils.StringPool;
import net.dreamlu.mica.redis.cache.CacheKey;
import org.springframework.util.ObjectUtils;

import java.time.Duration;

/**
 * @author dyun
 */
public class SmsUtils {

    public static final String PHONE_RULES = "^(\\+|00){0,2}(9[976]\\d|8[987530]\\d|6[987]\\d|5[90]\\d|42\\d|3[875]\\d|2[98654321]\\d|9[8543210]|8[6421]|6[6543210]|5[87654321]|4[987654310]|3[9643210]|2[70]|7|1)\\d{1,14}$";
    
    public static boolean checkPhoneNum(String phoneNumber) {
        return !ObjectUtils.isEmpty(phoneNumber) && phoneNumber.matches(PHONE_RULES);
    }

    /**
     * 短信验证码缓存key
     */
    public static CacheKey getSmsKey(String uuid) {
        // 格式key:模板标识:手机号
        return new CacheKey(OpsConstants.ALISMS_KEY + StringPool.COLON + uuid, Duration.ofMinutes(5));
    }

    /**
     * 生成短信验证码类
     */
    public static ValidateData generateValidateData(String uuid) {
        ValidateData validateData = new ValidateData();
        String smsCode = CacheTool.getSmsCode(uuid);
        validateData.setUuid(uuid);
        validateData.setCode(smsCode);
        return validateData;
    }

    /**
     * 验证短信验证码
     */
    public static boolean validate(String uuid, String code) {
        return code.equals(CacheTool.getMicaRedisCache().get(getSmsKey(uuid)));
    }
}
